package com.linkwechat.common.component.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.linkwechat.common.component.RedisService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @Author 王君平
 * @Date 2023/8/29 15:49
 * @Description
 */
@Slf4j
@Component
public class RedisServiceImpl implements RedisService {


    @Autowired
    private StringRedisTemplate  redisTemplate;



    @Override
    public void set(String key, Object value) {
        if(value instanceof String){
            redisTemplate.opsForValue().set(key, (String)value);
        }else {
            redisTemplate.opsForValue().set(key, JSON.toJSONString(value));
        }
    }

    @Override
    public void set(String key, Object value, Long expireTime) {
        if(value instanceof String){
            redisTemplate.opsForValue().set(key, (String)value,expireTime, TimeUnit.SECONDS);
        }else {
            redisTemplate.opsForValue().set(key, JSON.toJSONString(value), expireTime, TimeUnit.SECONDS);
        }
    }

    @Override
    public void remove(String... keys) {
        for (String key : keys) {
            remove(key);
        }
    }

    /**
     * 删除对应的value
     * @param key
     */
    private void remove(final String key) {
        if (exists(key)) {
            redisTemplate.delete(key);
        }
    }

    @Override
    public boolean exists(String key) {
        return redisTemplate.hasKey(key);
    }

    @Override
    public <T> T get(String key,Class<T> clazz) {
        if(clazz == String.class){
            return (T)redisTemplate.opsForValue().get(key);
        }
        return JSONObject.parseObject(redisTemplate.opsForValue().get(key), clazz);
    }

    @Override
    public <T> T get(String key, TypeReference<T> tTypeReference) {
        return JSON.parseObject(redisTemplate.opsForValue().get(key),tTypeReference);
    }

    @Override
    public void expire(String key, Long time, TimeUnit timeUnit) {
        redisTemplate.expire(key,time,timeUnit);
    }


}
